1. Introduction
Proxy patterns is useful to intercept calls to a property of and object using the built-in method new Proxy
on JS
2. Learning Objectives
- Objective 1: To describe the patter.
- Objective 2: To know the best practices of this pattern
- …
3. Key Concepts
- Proxies are objects that intercepts the request of the property of an object this is useful to validate before set the value.
- Proxy objects are commonly used to log property accesses, validate, format, or sanitize inputs, and so on.
4. Examples and Practical Cases
const person = {
name: "John Doe",
age: 42,
email: "john@doe.com",
country: "Canada",
};
const personProxy = new Proxy(person, {
get: (target, prop) => {
console.log(`The value of ${prop} is ${target[prop]}`);
return target[prop];
},
set: (target, prop, value) => {
console.log(`Changed ${prop} from ${target[prop]} to ${value}`);
target[prop] = value;
return true;
},
});
import { isValidEmail, isAllLetters } from './validator.js';
const user = {
firstName: 'John',
lastName: 'Doe',
username: 'johndoe',
age: 42,
email: 'john@doe.com',
};
const userProxy = new Proxy(user, {
get: (obj, prop) => {
return `${new Date()} | The value of ${prop} is ${Reflect.get(obj, prop)}`;
},
set: (obj, prop, value) => {
if (prop === 'email') {
if (!isValidEmail(value)) {
console.log('Please provide a valid email.');
return false;
}
}
if (prop === 'username') {
if (value.length < 3) {
throw new Error('Please use a longer username.');
} else if (!isAllLetters(value)) {
throw new Error('You can only use letters');
}
}
if (prop === 'age') {
if (typeof value !== 'number') {
throw new Error('Please provide a valid age.');
}
if (value < 18) {
throw 'User cannot be younger than 18.';
}
}
return Reflect.set(obj, prop, value);
},
});
5. Reflections and Synthesis
- Summary:
Summarize in a few lines what you learned and how it relates to other topics. - Open Questions:
A list of questions to further explore or research in the future. - Self-Assessment:
Personal reflections on your level of understanding and areas that need reinforcement.
6. Conclusion
A final recap and how it connects to your overall learning journey on FrontendMasters.